package main

import "fmt"

// Memento：只存状态，不暴露编辑器内容
type Memento struct {
	content string
}

// Originator：可编辑的对象，能创建和恢复备忘录
type Editor struct {
	content string
}

func (e *Editor) Write(text string) {
	e.content += text
}

func (e *Editor) CreateMemento() *Memento {
	return &Memento{content: e.content}
}

func (e *Editor) Restore(m *Memento) {
	e.content = m.content
}

func (e *Editor) Content() string {
	return e.content
}

// Caretaker：管理编辑历史，支持撤销
type Caretaker struct {
	history []*Memento
}

func (c *Caretaker) Save(m *Memento) {
	c.history = append(c.history, m)
}

func (c *Caretaker) Undo() *Memento {
	if len(c.history) == 0 {
		return nil
	}
	// 弹出最后一条记录
	last := c.history[len(c.history)-1]
	c.history = c.history[:len(c.history)-1]
	return last
}

func main() {
	editor := &Editor{}
	caretaker := &Caretaker{}

	// 初始写入
	editor.Write("Hello")
	caretaker.Save(editor.CreateMemento())
	fmt.Println("1:", editor.Content()) // Hello

	editor.Write(", World")
	caretaker.Save(editor.CreateMemento())
	fmt.Println("2:", editor.Content()) // Hello, World

	editor.Write("!!!")
	fmt.Println("3:", editor.Content()) // Hello, World!!!

	// 撤销最后一次操作
	m := caretaker.Undo()
	if m != nil {
		editor.Restore(m)
	}
	fmt.Println("After Undo:", editor.Content()) // Hello, World

	// 再次撤销
	m = caretaker.Undo()
	if m != nil {
		editor.Restore(m)
	}
	fmt.Println("After 2nd Undo:", editor.Content()) // Hello
}
